package com.leyou.auth.interceptor;

import com.leyou.auth.utils.UserHolder;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.CookieUtils;
import com.leyou.constants.JwtConstants;
import com.leyou.dto.Payload;
import com.leyou.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 付
 */
@Slf4j
public class Logininterceptor implements HandlerInterceptor {
    private JwtUtils jwtUtils;

    public Logininterceptor(JwtUtils jwtUtils) {
        this.jwtUtils = jwtUtils;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取cookie中的jwt
        String jwt = CookieUtils.getCookieValue(request, JwtConstants.COOKIE_NAME);
        //判断是否存在
        if (jwt==null){
            throw new LyException(401,"用户未登录");
        }
        //校验jwt
        Payload payload = jwtUtils.parseJwt(jwt);
        //存储用户信息
        UserHolder.setUser(payload.getUserDetail());
        UserHolder.setJwt(jwt);
        //正确放行
        log.debug("用户{}正在访问路径:{}",payload.getUserDetail().getUsername(),request.getRequestURI());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.jwtremove();
        UserHolder.userremove();
    }
}
